import 'package:flutter/material.dart';
import 'package:flutter_app/bean/list_app_article_entity.dart';
import 'package:flutter_app/values/MyColors.dart';
import 'package:flutter_app/widget/custom_app_bar.dart';
import 'package:flutter_app/widget/empty_view.dart';
import 'package:flutter_screenutil/src/size_extension.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../r.dart';
import 'news_logic.dart';

/**
 * @Description: 要闻
 * @Author: 下雨了
 * @Version: 1.0
 */
///
class NewsPage extends StatefulWidget {
  final String title;

  const NewsPage({Key? key, required this.title}) : super(key: key);

  @override
  _NewsPageState createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage> {
  final logic = Get.put(NewsLogic());
  final state = Get.find<NewsLogic>().state;

  // 刷新控制器 initialRefresh 是否最初刷新
  late RefreshController refreshController = RefreshController(initialRefresh: false);

  /// 刷新
  void onRefresh() async {
    state.currentPage.value = 1;
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果失败,使用refreshFailed ()
    logic.postListArticle(state.currentPage.value).then((_) {
      refreshController.refreshCompleted();
      refreshController.resetNoData();
    });
  }

  /// 加载
  void onLoading() async {
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果完成使用loadFailed()，如果没有数据返回，使用LoadNodata()
    int totalPages = state.listAppArticleEntity?.totalPages ?? 1;

    if (state.currentPage.value < totalPages) {
      state.currentPage.value++;
      logic.postListArticle(state.currentPage.value).then((_) {
        refreshController.loadComplete();
      });
    } else {
      refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<NewsLogic>(builder: (logic) {
      return Scaffold(
        appBar: MyAppBar(context, title: "要闻"),
        body: Container(
          color: MyColors.FFF1F1F1,
          child: Stack(
            children: [
              Image.asset(R.assetsImgBg112),
              Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(topRight: Radius.circular(15.r), topLeft: Radius.circular(15.r)),
                    color: MyColors.FFFFFFFF
                ),
                child: SmartRefresher(
                  controller: refreshController,
                  //  允许下拉刷新
                  enablePullDown: true,
                  // 允许上拉加载
                  enablePullUp: true,
                  // 刷新
                  onRefresh: onRefresh,
                  // 加载
                  onLoading: onLoading,
                  header: WaterDropHeader(complete: Text('刷新完成', style: TextStyle(color: MyColors.FF333333))),
                  footer: ClassicFooter(loadingText: '加载中...', idleText: '上拉加载更多..', noDataText: '没有更多数据了'),
                  child: (state.listAppArticleEntity?.content?.length ?? 0) > 0 ? ListView.separated(
                    itemCount: state.listAppArticleEntity?.content?.length ?? 0,
                    physics: BouncingScrollPhysics(),
                    itemBuilder: (context, index) {
                      return NewsListItem(state.listAppArticleEntity!.content![index]);
                    },
                    separatorBuilder: (BuildContext context, int index) {
                      return Container(
                        height: 0.5.r,
                        color: MyColors.FFDDDDDD,
                      );
                    },
                  ) : EmptyView(),
                ),
              )
            ],
          ),
        ),
      );
    });
  }

  Widget NewsListItem(ListAppArticleContent item) {
    return Container(
      padding: EdgeInsets.only(top: 16.r, bottom: 16.r, right: 14.r, left: 14.r),
      child: IntrinsicHeight(
        child: InkWell(
          child: item.pictureList!.length == 1 ? Row(
            children: [
              Expanded(
                child: Container(
                  padding: EdgeInsets.only(top: 1.r, bottom: 1.r),
                  margin: EdgeInsets.only(right: 13.r),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(item.title ?? "",
                        style: TextStyle(color: Colors.black, fontSize: 16.sp,
                          fontWeight: FontWeight.w500, height: 1.2.r,
                        ),
                        textAlign: TextAlign.justify,
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                      Container(
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Flexible(child: Text(item.xSource ?? "", maxLines: 1, style: TextStyle(color: MyColors.FF999999, fontSize: 12.sp),)),
                            SizedBox(width: 5.r,),
                            Text(item.publishTime!, style: TextStyle(color: MyColors.FF999999, fontSize: 12.sp),)
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 90.r,
                width: 110.r,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4.r),
                  child: Image.network(
                    item.pictureList?[0].thumbnailPath ?? "",
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ],
          )
          : item.pictureList!.length > 1 && item.pictureList!.length < 4 ?
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(item.title ?? "",
                  style: TextStyle(color: Colors.black, fontSize: 16.sp, fontWeight: FontWeight.w500, height: 1.2.r,),
                  maxLines: 2,
                  textAlign: TextAlign.justify,
                  overflow: TextOverflow.ellipsis,
                ),
                Container(
                  margin: EdgeInsets.only(top: 8.r),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      for (ListAppArticleContentPictureList picture in item.pictureList!)
                        SizedBox(
                          height: 90.r,
                          width: 110.r,
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(4.r),
                            child: Image.network(
                              picture.thumbnailPath ?? "",
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 8.5.r),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Flexible(child: Text(item.xSource ?? "", maxLines: 1, style: TextStyle(color: MyColors.FF999999, fontSize: 12.sp),)),
                      SizedBox(width: 5.r,),
                      Text(item.publishTime!, style: TextStyle(color: MyColors.FF999999, fontSize: 12.sp),)
                    ],
                  ),
                )
              ],
            )
            : Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(item.title ?? "",
                  style: TextStyle(color: Colors.black, fontSize: 16.sp, fontWeight: FontWeight.w500, height: 1.2.r),
                  maxLines: 2,
                  textAlign: TextAlign.justify,
                  overflow: TextOverflow.ellipsis,
                ),
                Container(
                  margin: EdgeInsets.only(top: 7.5.r),
                  child: Text((item.content ?? "").trim(),
                    style: TextStyle(color: MyColors.FF333333, fontSize: 13.sp, height: 1.25.r),
                    maxLines: 2,
                    textAlign: TextAlign.justify,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 8.5.r),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Flexible(child: Text(item.xSource ?? "", maxLines: 1, style: TextStyle(color: MyColors.FF999999, fontSize: 12.sp),)),
                      SizedBox(width: 5.r,),
                      Text(item.publishTime ?? "", style: TextStyle(color: MyColors.FF999999, fontSize: 12.sp),)
                    ],
                  ),
                )
              ],
            ),
            onTap: () {
              logic.goToNewsDetailPage(item.id);
            }
        ),
      ),
    );
  }

  @override
  void dispose() {
    Get.delete<NewsLogic>();
    super.dispose();
  }
}